/**
 * 封装网络请求
 */

import axios from 'axios'
import type { AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'

interface requestOptions {
  url: string
  data?: object
  method?: 'POST' | 'GET' | 'DELETE' | 'PUT'
  /** 是否返回原始数据，默认 false */
  raw?: boolean
  /** 是否展示错误信息，默认 true */
  showErr?: boolean
}

// 发布需修改
// 生产环境
// const baseUrl = 'https://www.lyeen.com/'
// 本地测试
const baseUrl = '/api'

const request = async ({
  url,
  data = {},
  method = 'POST',
  raw = false,
  showErr = true
}: requestOptions) => {
  try {
    const requestOptions: AxiosRequestConfig = {
      url: url,
      baseURL: baseUrl,
      method: method
    }
    if (method === 'GET') {
      requestOptions.params = data
    } else {
      requestOptions.data = data
    }
    const res = await axios.request(requestOptions)
    /** res.data 后台返回数据格式
     * {
     *   body: {},
     *   code: 0, 0-成功 1-失败
     *   errMsg: ''
     * }
     */
    if (raw) {
      return res.data
    } else {
      if (res.data.code === 0) {
        return res.data.body
      } else {
        if (showErr) {
          ElMessage.error(res.data.errMsg || '接口异常')
        }
        console.log(res.data.errMsg || '接口异常')
      }
    }
  } catch (error: any) {
    ElMessage.error(error.message || '接口访问失败')
    console.log(error.message || '接口访问失败')
  }
}

export { baseUrl, request }
